<template>
  <div>
    <h1 id="last">现金流出</h1>
    <div class="controls">
      <input v-model="searchQuery" type="text" placeholder="搜索支出项目" @input="applyFilters" />
      开始日期： <input v-model="startDate" type="date" @change="applyFilters" />
      截止日期：<input v-model="endDate" type="date" @change="applyFilters" />
      <button class="repeat" @click="resetFilters">重置</button>
      <button class="add" @click="showPopup">新增</button>
      <button class="out" @click="exportExcel">导出excel文件</button>
    </div>
    <table class="tab" id="cashTable">
      <thead>
        <tr>
          <th>支出项目</th>
          <th>金额</th>
          <th>时间</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, index) in paginatedData" :key="item.id">
          <td>{{ item.outcome_item }}</td>
          <td>{{ item.amount }}</td>
          <td>{{ item.date }}</td>
          <td>
            <button class="bianji" @click="editItem(item)">编辑</button>
            <button class="shanchu" @click="deleteItem(item)">删除</button>
          </td>
        </tr>
        <tr>
          <td colspan="1">合计</td>
          <td>{{ totalAmount }}</td>
          <td colspan="2"></td>
        </tr>
      </tbody>
    </table>
    <div class="pagination">
      <button @click="prevPage" :disabled="currentPage === 1">上一页</button>
      <span>第 {{ currentPage }} 页，共 {{ totalPages }} 页</span>
      <button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
    </div>

    <!-- 新增弹窗 -->
    <div v-if="showAddPopup" class="popup">
      <div class="popup-content">
        <span class="close" @click="showAddPopup = false">&times;</span>
        <h2>新增支出</h2>
        <label for="item">支出项目：</label>
        <input v-model="newItem.item" type="text" id="item" placeholder="请输入:" />
        <label for="amount">金额：</label>
        <input v-model="newItem.amount" type="number" id="amount" placeholder="请输入:" />
        <label for="date">时间：</label>
        <input v-model="newItem.date" type="date" id="date" />
        <button @click="addItem">提交保存</button>
      </div>
    </div>

    <!-- 编辑弹窗 -->
    <div v-if="showEditPopup" class="popup">
      <div class="popup-content">
        <span class="close" @click="showEditPopup = false">&times;</span>
        <h2>编辑支出</h2>
        <label for="editItem">支出项目：</label>
        <input v-model="editItemData.item" type="text" id="editItem" placeholder="请输入:" />
        <label for="editAmount">金额：</label>
        <input v-model="editItemData.amount" type="number" id="editAmount" placeholder="请输入:" />
        <label for="editDate">时间：</label>
        <input v-model="editItemData.date" type="date" id="editDate" />
        <button @click="updateItem">更新</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import * as XLSX from 'xlsx';

const cashData = ref([]);
const showAddPopup = ref(false);
const showEditPopup = ref(false);
const newItem = ref({
  item: '',
  amount: 0,
  date: ''
});
const editItemData = ref({
  id: null,
  item: '',
  amount: 0,
  date: ''
});
const searchQuery = ref('');
const startDate = ref('');
const endDate = ref('');
const currentPage = ref(1);
const itemsPerPage = 8;
const userId = ref(null);

const fetchCashData = async () => {
  try {
    const response = await fetch(`http://82.156.19.25:5000/get_outcome_data?user_id=${userId.value}`);
    const data = await response.json();
    if (data.success) {
      cashData.value = data.outcome;
    } else {
      alert(data.message);
    }
  } catch (error) {
    console.error('获取数据失败', error);
  }
};

const showPopup = () => {
  showAddPopup.value = true;
};

const applyFilters = () => {
  currentPage.value = 1;
};

const resetFilters = () => {
  searchQuery.value = '';
  startDate.value = '';
  endDate.value = '';
  applyFilters();
};

const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--;
  }
};

const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++;
  }
};

const addItem = async () => {
  if (newItem.value.item && newItem.value.amount && newItem.value.date) {
    try {
      const response = await fetch('http://82.156.19.25:5000/add_outcome_data', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          user_id: userId.value,
          outcome_item: newItem.value.item,
          amount: newItem.value.amount,
          date: newItem.value.date
        })
      });
      const data = await response.json();
      if (data.success) {
        // 刷新页面以显示最新数据
        window.location.reload();
      } else {
        alert(data.message);
      }
    } catch (error) {
      console.error('添加数据失败', error);
    }
  } else {
    alert('请完整填写所有字段。');
  }
};

const resetNewItem = () => {
  newItem.value = {
    item: '',
    amount: 0,
    date: ''
  };
};

const editItem = (item) => {
  editItemData.value = { ...item };
  showEditPopup.value = true;
};

const updateItem = async () => {
  if (editItemData.value.item && editItemData.value.amount && editItemData.value.date) {
    try {
      const response = await fetch('http://82.156.19.25:5000/update_outcome_data', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          user_id: userId.value,
          id: editItemData.value.id,
          outcome_item: editItemData.value.item,
          amount: editItemData.value.amount,
          date: editItemData.value.date
        })
      });
      const data = await response.json();
      if (data.success) {
        fetchCashData();
        showEditPopup.value = false;
      } else {
        alert(data.message);
      }
    } catch (error) {
      console.error('更新数据失败', error);
    }
  } else {
    alert('请完整填写所有字段。');
  }
};

const deleteItem = async (item) => {
  try {
    // 弹出确认框，询问是否确定删除
    const isConfirmed = confirm(`确定要删除"${item.outcome_item}"这条数据吗？`);

    if (!isConfirmed) {
      return; // 如果用户取消删除，则直接返回
    }

    const response = await fetch('http://82.156.19.25:5000/delete_outcome_data', {
      method: 'DELETE',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        user_id: userId.value,
        id: item.id
      })
    });

    const data = await response.json();

    if (data.success) {
      fetchCashData(); // 删除成功后，重新获取数据以更新表格
    } else {
      alert(data.message); // 如果删除失败，显示错误信息
    }
  } catch (error) {
    console.error('删除数据失败', error); // 如果请求失败，记录错误信息
  }
};

const filteredData = computed(() => {
  return cashData.value
    .filter(item => {
      const matchesSearch = item.outcome_item.includes(searchQuery.value);
      const matchesStartDate = !startDate.value || new Date(item.date) >= new Date(startDate.value);
      const matchesEndDate = !endDate.value || new Date(item.date) <= new Date(endDate.value);
      return matchesSearch && matchesStartDate && matchesEndDate;
    })
    .sort((a, b) => b.id - a.id); // 按 id 逆序排列
});

const totalPages = computed(() => {
  return Math.ceil(filteredData.value.length / itemsPerPage);
});

const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * itemsPerPage;
  const end = start + itemsPerPage;
  return filteredData.value.slice(start, end);
});

const totalAmount = computed(() => {
  return filteredData.value.reduce((total, item) => total + parseFloat(item.amount), 0);
});
// 导出 Excel 文件
const exportExcel = () => {
  // 获取表格数据
  const tableData = filteredData.value.map(item => [
    item.outcome_item, // 支出项目
    item.amount,       // 金额
    item.date          // 时间
  ]);

  // 添加表头
  tableData.unshift(['支出项目', '金额', '时间']);
  // 计算金额的总数
  const totalAmount = filteredData.value.reduce((sum, item) => sum + parseFloat(item.amount || 0), 0);
  // 添加总金额行
  tableData.push(['总金额', totalAmount.toFixed(2), '']);
  // 创建工作表
  const worksheet = XLSX.utils.aoa_to_sheet(tableData);
  // 自动调整列宽
  const columnWidths = tableData[0].map((_, colIndex) => {
    const maxLength = Math.max(...tableData.map(row => (row[colIndex] ? row[colIndex].toString().length : 0)));
    return { width: maxLength + 5 }; // 给每列的宽度加上一定的缓冲
  });
  worksheet['!cols'] = columnWidths;
  // 创建工作簿并添加工作表
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');

  // 导出 Excel 文件
  XLSX.writeFile(workbook, '支出表.xlsx');
};

onMounted(() => {
  userId.value = localStorage.getItem('userId');
  if (userId.value) {
    fetchCashData();
  } else {
    alert('请先登录');
    window.location.href = '/login';
  }
});
</script>


  
  <style scoped>
  .controls {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
.controls input[type='text']{
  margin-left: 125px;
  margin-right: 10px;
  padding: 5px;
  border-radius: 4px;
  border: 1px solid #ddd;
}
.controls input[type='month'],
.controls input[type='date'] {
  margin-left: 1px;
  margin-right: 10px;
  padding: 5px;
  border-radius: 4px;
  border: 1px solid #ddd;
}

table {
  border-collapse: collapse;
  width: 100%;
}

table {
  border-collapse: collapse;
  width: 80%;
  margin: 20px 0;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  background-color: #fff;
}

th,
td {
  border: 1px solid #ddd;
  padding: 12px 15px;
  text-align: center;
}

th {
  background-color: #4caf50;
  color: white;
}

tr:nth-child(even) {
  background-color: #f2f2f2;
}

tr:hover {
  background-color: #f1f1f1;
}

h1 {
  margin-left: 15px;
}
.repeat{
  background-color: rgb(134, 173, 16);
  margin-bottom: 5px;
  margin-top: 10px;
  margin-left: 10px;
  border-radius: 8px;
  border-style: none;
  padding: 5px 20px;
  font-size: 15px;
  color: white;
  transition: background-color 0.3s; /* 添加过渡效果 */
}
.add {
  background-color: rgb(27, 128, 7);
  margin-bottom: 5px;
  margin-top: 10px;
  margin-left: 10px;
  border-radius: 8px;
  border-style: none;
  padding: 5px 20px;
  font-size: 15px;
  color: white;
  transition: background-color 0.3s; /* 添加过渡效果 */
}
.out:hover,
.add:hover,
.bianji:hover,
.shanchu:hover {
  background-color: rgb(103, 17, 240);
}

.out {
  background-color: #f07c3e;
  margin-bottom: 5px;
  margin-top: 10px;
  margin-left: 10px;
  border-radius: 8px;
  border-style: none;
  padding: 5px 20px;
  font-size: 15px;
  color: white;
  transition: background-color 0.3s;
}

.popup {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.popup-content {
  background-color: white;
  padding: 20px;
  border-radius: 5px;
  width: 300px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
  position: relative;
}

.close {
  position: absolute;
  right: 20px;
  top: 20px;
  cursor: pointer;
  font-size: 18px;
  color: #333;
}

.bianji {
  background-color: rgb(201, 43, 31);
  margin-bottom: 10px;
  margin-top: 10px;
  margin-left: 10px;
  border-radius: 8px;
  border-style: none;
  padding: 5px 20px;
  font-size: 15px;
  color: white;
  transition: background-color 0.3s; /* 添加过渡效果 */
}
.tab {
  margin-left: 125px;
}
.shanchu {
  background-color: rgb(9, 4, 48);
  margin-bottom: 10px;
  margin-top: 10px;
  margin-left: 10px;
  border-radius: 8px;
  border-style: none;
  padding: 5px 20px;
  font-size: 15px;
  color: white;
  transition: background-color 0.3s; /* 添加过渡效果 */
}

button {
  cursor: pointer;
}
.popup-content input[type='month'],
.popup-content input[type='text'],
.popup-content input[type='number'],
.popup-content input[type='date'] {
  width: 100%;
  padding: 8px;
  margin-bottom: 15px;
  border-radius: 4px;
  border: 1px solid #ddd;
  font-size: 14px;
}

input[type='text']:focus,
input[type='number']:focus,
input[type='month']:focus,
input[type='date']:focus {
  border-color: #4caf50;
}


button {
  background-color: #4caf50;
  color: white;
  border: none;
  border-radius: 5px;
  padding: 12px 24px;
  cursor: pointer;
  margin-top: 10px;
  transition: background-color 0.3s;
}

button:hover {
  background-color: #45a049;
}


.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
}

.pagination button {
  margin: 0 5px;
  padding: 8px 16px;
  border-radius: 4px;
  background-color: #f2f2f2;
  color: #333;
  border: none;
  cursor: pointer;
  transition: background-color 0.3s;
}

.pagination button:hover {
  background-color: #ddd;
}
  
  </style>
  